package edu.zcmu.seckill.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @Author: tang
 * @Date: 2022/1/11/13:58
 * @Description:
 */
@Slf4j
@Controller
public class FileController {

    @Autowired
    OSS ossClient;
    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;
    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;
    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;
    @RequestMapping(value = "/file/upload",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject fileUpload(@RequestParam(value = "file", required = true)  MultipartFile file) throws IOException {

        String uri="https://mall-ts.oss-cn-shanghai.aliyuncs.com/";
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);
        String filename = "ts-"+ UUID.randomUUID().toString().replaceAll("-", "");
        ossClient.putObject("mall-ts",filename+fileName,file.getInputStream());
        JSONObject res = new JSONObject();
        res.put("url", uri+filename+fileName);
        res.put("success", 1);
        res.put("message", "upload success!");
        log.info("上传图片成功");
        return res;
    }


}
